package app

import (
	"APT/internal/consts"
	"APT/internal/dao"
	"APT/internal/library/contexts"
	"APT/internal/library/hgorm/hook"
	"APT/internal/model"
	"APT/internal/model/entity"
	"APT/internal/service"
	"context"
	"database/sql"
	"errors"
	"fmt"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"

	"APT/api/app/basics"
)

func (c *ControllerBasics) ShareInfo(ctx context.Context, req *basics.ShareInfoReq) (res *basics.ShareInfoRes, err error) {
	var (
		MemberInfo    = contexts.GetMemberUser(ctx)
		PmsProperty   entity.PmsProperty
		WXShareConfig *model.WXShareConfig
	)
	if WXShareConfig, err = service.BasicsConfig().GetWXShareConfig(ctx); err != nil {
		return
	}
	res = new(basics.ShareInfoRes)
	switch contexts.GetLanguage(ctx) {
	case consts.Zh:
		res.Title = WXShareConfig.TitleZh
		res.Content = WXShareConfig.ContentZh
		break
	case consts.En:
		res.Title = WXShareConfig.TitleEn
		res.Content = WXShareConfig.ContentEn
		break
	case consts.Ko:
		res.Title = WXShareConfig.TitleKo
		res.Content = WXShareConfig.ContentKo
		break
	case consts.Ja:
		res.Title = WXShareConfig.TitleJa
		res.Content = WXShareConfig.ContentJa
		break
	case consts.ZhCN:
		res.Title = WXShareConfig.TitleZhCn
		res.Content = WXShareConfig.ContentZhCn
		break
	default:
		err = gerror.New("语言格式错误")
		return
	}
	res.Icon = WXShareConfig.Icon
	res.Url = WXShareConfig.ShareUrl
	if req.ShareType == "member" {
		res.Url = fmt.Sprintf("%s?referrer=%d", res.Url, MemberInfo.Id)
	} else if req.ShareType == "host" {
		if err = dao.PmsProperty.Ctx(ctx).
			Where(dao.PmsProperty.Columns().Id, req.Pid).
			Hook(hook.PmsFindLanguageValueHook).
			Scan(&PmsProperty); err != nil && !errors.Is(err, sql.ErrNoRows) {
			return
		}
		if g.IsEmpty(PmsProperty) {
			g.Log().Info(ctx, "物业不存在", err)
			return
		}
		res.Url = fmt.Sprintf("%s?referrer=%d&Property=%s", res.Url, MemberInfo.Id, PmsProperty.Uid)
	}
	return
}

func (c *ControllerBasics) ShareInvitePageInfo(ctx context.Context, req *basics.ShareInvitePageInfoReq) (res *basics.ShareInvitePageInfoRes, err error) {
	var (
		MemberInfo *model.MemberIdentity
	)
	MemberInfo = contexts.GetMemberUser(ctx)
	res = new(basics.ShareInvitePageInfoRes)
	if MemberInfo.RebateMode == "CHANNEL" || MemberInfo.RebateMode == "STAFF" {
		// 渠道
		res.AwardScore = 1000
		res.AwardCommission = 1
		res.WithdrawPrice = MemberInfo.Balance
		res.GetCommission = 450000
		res.SuccessMember = 1
	} else {
		// 会员
		res.AwardScore = 1000
		res.AwardCommission = 1
		res.GetScore = 1000
		res.SuccessMember = 1
	}
	return
}
